var app = getApp();
import wxbarcode from 'wxbarcode';
Page({
  data: {
    // 订单列表数据
    orders: [],
    // 筛选后的订单
    filteredOrders: [],
    // 当前激活的状态筛选
    activeStatus: '',
    // 核销码弹窗
    showVerifyModal: false,
    hexiaoCode: '',
	start: 0,	
	showBarcodeModal:false
  },
	onShow: function () {
		
	},
  onLoad() {
    // 加载订单数据
	let self = this
	app.util.getUserInfo(function (response) {
		self.setData({
			userInfo: response
		});
		app.mdInit(function (cfg,mine,area) {
			self.setData({
				cfg: cfg,
				mine:mine,
				area:area
			});
			
			self.loadOrders();
		});
	});
  },

  // 手机号脱敏处理（中间4位替换为*）
  formatPhone(phone) {
    if (!phone) return '';
    return phone.replace(/^(\d{3})(\d{4})(\d{4})$/, '$1****$3');
  },

  // 加载订单数据
  loadOrders() {
    // 模拟数据（实际项目中从接口获取）
    const self = this;
	app.util.request({
		url: 'Physical/orderlist',
		data: {
			m: app.mdName,
			filt:self.data.activeStatus
		},
		success(res) {
			var data = res.data.data;
			console.log(data);
			var list = new Array();
			list = list.concat(data.list);
			console.log('list:',list)
			self.setData({
				now:data.now,
				orders: list,
				start: data.start,
				more: data.more
			});
			// 处理订单数据：格式化手机号+处理项目显示
			const processedOrders = self.data.orders.map(order => {
			  // 手机号脱敏处理
			  const formattedPhone = self.formatPhone(order.personPhone);
			  
			  const totalProjects = order.projects.length;
			  // 默认显示前3项，展开后显示全部
			  const showProjects = order.isExpanded 
			    ? order.projects 
			    : order.projects.slice(0, 3);
			  
			  return {
			    ...order,
			    personPhone: formattedPhone, // 替换为脱敏后的手机号
			    totalProjects,
			    showProjects
			  };
			});
			
			self.setData({
			  orders: processedOrders,
			  filteredOrders: processedOrders
			});
		}
	})
    
  },

  // 切换订单状态筛选
  changeStatus(e) {
    const status = e.currentTarget.dataset.status;
    this.setData({ activeStatus: status });

    // 根据状态筛选订单
    const filtered = status 
      ? this.data.orders.filter(order => order.status === parseInt(status))
      : this.data.orders;
    
    this.setData({ filteredOrders: filtered });
  },

  // 展开/收回项目列表
  toggleProjects(e) {
    const index = e.currentTarget.dataset.index;
    const orders = [...this.data.orders];
    // 切换展开状态
    orders[index].isExpanded = !orders[index].isExpanded;
    // 更新显示的项目
    orders[index].showProjects = orders[index].isExpanded
      ? orders[index].projects
      : orders[index].projects.slice(0, 3);
    
    // 更新筛选后的列表
    const filteredOrders = this.data.activeStatus
      ? orders.filter(order => order.status === parseInt(this.data.activeStatus))
      : orders;
    
    this.setData({
      orders,
      filteredOrders
    });
  },


  // 关闭核销码弹窗
  closeVerifyModal() {
    this.setData({ showVerifyModal: false });
  },

  // 查看报告
  goToReport(e) {
    const orderId = e.currentTarget.dataset.orderid;
	console.log(orderId)
	let tempId=['tF3JZheCj1qEyZq5rwHr81CvuJQOd_yiL6Lbuj_qV2Q'];
	wx.requestSubscribeMessage({
	  tmplIds: tempId,
	  success (res) {
		if (res[tempId] === 'accept') {
		  console.log('用户同意了')  
	  
		}else if(res[tempId] == 'reject') { // 用户拒绝授权
		  wx.showModal({
			title: '温馨提示',
			content: "您已关闭消息推送，如需要消息推送服务，请点击确定跳转设置页面打开授权后再次尝试。",
			success: function(modal) {
				if (modal.confirm) { // 点击确定
					wx.openSetting({ withSubscriptions: true })
				}
			}
		})
		}
	   },
	   fail(err) { 
		 console.log(err)
		 if (err.errCode == '20004') {
		  wx.showModal({
			  title: '温馨提示',
			  content: "您的消息订阅主已关闭，如需复习提醒服务，请点击确定跳转设置页面打开授权后再次尝试。",
			  success: function(modal) {
				  if (modal.confirm) { // 点击确定
					  wx.openSetting({ withSubscriptions: true })
				  }
			  }
		  })
	  }
		},
		complete(s) {			
			wx.navigateTo({
			  url: `/vp_pz/pages/physicalExam/reportDetail/reportDetail?orderId=${orderId}`
			});
		}
	})
  },

  // 去首页
  goToHome() {
    wx.switchTab({ url: '/vp_pz/pages/physicalExam/packageList/packageList' });
  },
  // 核销操作
    handleVerify(e) {
		const self = this
		self.setData({
			hexiaoCode:e.currentTarget.dataset.code
		})
		this.generateBarcode(e.currentTarget.dataset.code)
     
    },
  // 生成条形码
    generateBarcode(couponCode) {    
  
      // 生成条形码
      wxbarcode.qrcode('qrcode', couponCode, 600, 600);
      console.log(couponCode)
      // 显示弹窗
      this.setData({
        showBarcodeModal: true
      });
    },
  
    // 关闭弹窗
    closeModal() {
      this.setData({
        showBarcodeModal: false
      });
    },
});